/* eslint-disable no-nested-ternary */
import {Form, Row, Col, Input, Select, DatePicker, InputNumber} from 'antd'
import React, {
	useState,
	useEffect,
	useImperativeHandle,
	forwardRef,
} from 'react'
import { head } from 'lodash';
import moment from 'moment'
import styles from '../index.less'
import UploadAvatar from '@/components/UploadAvatar'
import { getImageUrlList, IImageItemResponse } from '@/utils/image'

const {TextArea} = Input

type propsType = {
	data: any
	type: string
	dictData: any
	enclosureList: any[]
}

// 全局定义所有车辆保险相关的图片与后端约定好的index。不可前端做修改需保证与后端一致
const ImeagTargetAttrIndex = {
	compulsory: 1, // 交强险保单照片
	commercial: 2, // 商业险保单照片
	carrier: 3, // 承运险保单照片
}
const customizeHeader = (value: string) => (
	<span>
		<div className={styles.tip} />
		{value}
	</span>
)

/** 停延保状态 */
const getOutOfWarranty = (text: string | number) => {
	if (text === 1) {
		return '正常'
	}
	if (text === 2) {
		return '停保中'
	}
	if (text === 3) {
		return '延保中'
	}
	return '-'
}

const insuranceCard = (
	props: propsType,
	ref: React.Ref<unknown> | undefined,
) => {
	const { data, type, dictData } = props
	const [compulsoryForm] = Form.useForm()
	const [commercialForm] = Form.useForm()
	const [carrierForm] = Form.useForm()
	const [compulsoryUrl, setCompulsoryUrl] = useState<(IImageItemResponse | null)[]>()
	const [commercialUrl, setCommercialUrl] = useState<(IImageItemResponse | null)[]>()
	const [carrierUrl, setCarrierUrl] = useState < (IImageItemResponse | null)[]>()

	const formatDate = (formData: any, dateType?: string) => {
		const newData = formData
		const key: any = Object.keys(newData)
		if (key?.length) {
			key?.forEach((item: string) => {
				if (
					item.indexOf('Time') !== -1 ||
					item.indexOf('Deadline') !== -1
				) {
					if (newData[item]) {
						newData[item] = dateType
							? moment(newData[item]).format(dateType)
							: moment(newData[item])
					} else {
						newData[item] = ''
					}
				}
			})
		}

		return newData
	}
	// 设置保险单图片信息
	const setImageInfo = (data: any) => {
		const compulsoryPicId = head(data?.compulsoryPhotos) as string;
		if (compulsoryPicId) {
			const pic = getImageUrlList([{
				name: '交强险',
				id: compulsoryPicId,
				targetAttr: ImeagTargetAttrIndex.compulsory,
			}])
			setCompulsoryUrl(pic);
		}
		const commercialPicId = head(data?.commercialPhotos) as string;
		if (commercialPicId) {
			const pic = getImageUrlList([{
				name: '商业险',
				id: commercialPicId,
				targetAttr: ImeagTargetAttrIndex.commercial,
			}])
			setCommercialUrl(pic);
		}
		const carrierPicId = head(data?.carrierPhotos) as string;
		if (carrierPicId) {
			const pic = getImageUrlList([{
				name: '承运险',
				id: carrierPicId,
				targetAttr: ImeagTargetAttrIndex.carrier,
			}])
			setCarrierUrl(pic);
		}
	}
	useEffect(() => {
		if (data) {
			if (data?.compulsory) {
				compulsoryForm.setFieldsValue({
					...formatDate(data?.compulsory),
					compulsoryPhotos: data?.compulsoryPhotos?.[0],
				})
			}
			if (data?.commercial) {
				commercialForm.setFieldsValue({
					...formatDate(data?.commercial),
					commercialPhotos: data?.commercialPhotos?.[0],
				})
			}
			if (data?.carrier) {
				carrierForm.setFieldsValue({
					...formatDate(data?.carrier),
					carrierPhotos: data?.carrierPhotos?.[0],
				})
			}
		}
		setImageInfo(data);
	}, [data]);

	const onSubmit = async () => {
		const compulsoryValue = await compulsoryForm.validateFields()
		const commercialValue = await commercialForm.validateFields()
		const carrierValue = await carrierForm.validateFields()
		if (compulsoryValue && commercialValue && carrierValue) {
			const newData: any = {
				compulsoryPhotos: compulsoryValue?.compulsoryPhotos
					? [compulsoryValue?.compulsoryPhotos?.toString()]
					: [],
				commercialPhotos: commercialValue?.commercialPhotos
					? [commercialValue?.commercialPhotos?.toString()]
					: [],
				carrierPhotos: carrierValue?.carrierPhotos
					? [carrierValue?.carrierPhotos?.toString()]
					: [],
			}
			const dictCompulsory = dictData?.compulsory_company_code?.find(
				(item: {dictKey: any}) =>
					item?.dictKey === compulsoryValue?.compulsoryCompanyCode,
			)
			const dictCommercial = dictData?.commercial_company_code?.find(
				(item: {dictKey: any}) =>
					item?.dictKey === commercialValue?.commercialCompanyCode,
			)
			const dictCarrier = dictData?.carrier_company_code?.find(
				(item: {dictKey: any}) =>
					item?.dictKey === carrierValue?.carrierCompanyCode,
			)
			if (compulsoryValue?.id) {
				newData.compulsory = {
					...formatDate(compulsoryValue, 'YYYY-MM-DD HH:mm:ss'),
					compulsoryCompanyName: dictCompulsory?.dictValue,
				}
			}
			if (commercialValue?.id) {
				newData.commercial = {
					...formatDate(commercialValue, 'YYYY-MM-DD HH:mm:ss'),
					commercialCompanyName: dictCommercial?.dictValue,
				}
			}
			if (carrierValue?.id) {
				newData.carrier = {
					...formatDate(carrierValue, 'YYYY-MM-DD HH:mm:ss'),
					carrierCompanyName: dictCarrier?.dictValue,
				}
			}
			return newData
		}
		return {}
	}
	useImperativeHandle(ref, () => ({
		getData: onSubmit,
	}))
	const getUpload = (insuranceTypes: string) => {
		if (insuranceTypes === 'compulsory') {
			const uploadProps = {
				text: '上传保单',
				modelName: 'insurance',
				targetAttr: 1,
				accept: 'image/jpg,image/png',
				moreNum: 1,
				list: compulsoryUrl,
				callback: (res: any) => {
					compulsoryForm.setFieldsValue({
						compulsoryPhotos: res?.file?.response?.data?.id,
					})
				},
			}
			return <UploadAvatar {...uploadProps} />
		}
		if (insuranceTypes === 'commercial') {
			const uploadProps = {
				text: '上传保单',
				modelName: 'insurance',
				targetAttr: 2,
				accept: 'image/jpg,image/png',
				moreNum: 1,
				list: commercialUrl,
				callback: (res: any) => {
					commercialForm.setFieldsValue({
						commercialPhotos: res?.file?.response?.data?.id,
					})
				},
			}
			return <UploadAvatar {...uploadProps} />
		}
		if (insuranceTypes === 'carrier') {
			const uploadProps = {
				text: '上传保单',
				modelName: 'insurance',
				targetAttr: 3,
				accept: 'image/jpg,image/png',
				moreNum: 1,
				list: carrierUrl,
				callback: (res: any) => {
					carrierForm.setFieldsValue({
						carrierPhotos: res?.file?.response?.data?.id,
					})
				},
			}
			return <UploadAvatar {...uploadProps} />
		}
		return <></>
	}
	const getInsuranceName = (insuranceTypes: string) => {
		if (insuranceTypes === 'compulsory') {
			return '交强险保单号'
		}
		if (insuranceTypes === 'commercial') {
			return '商业险保单号'
		}
		if (insuranceTypes === 'carrier') {
			return '承运险保单号'
		}
		return ''
	}
	const getForm = (status: number, types: string) => (
		<>
			<Form.Item label="id" name="id" hidden>
				<Input placeholder="请输入" />
			</Form.Item>
			<Form.Item label={`${types}Photos`} name={`${types}Photos`} hidden>
				<Input placeholder="请输入" />
			</Form.Item>
			<Row gutter={12}>
				<Col span={8}>{getUpload(types)}</Col>
				<Col span={16}>
					<Row gutter={12}>
						<Col sm={{span: 24}} md={{span: 12}}>
							<Form.Item
								label={getInsuranceName(types)}
								name={`${types}No`}>
								<Input placeholder="请输入" />
							</Form.Item>
						</Col>
						<Col sm={{span: 24}} md={{span: 12}}>
							<Form.Item
								label="保险公司"
								name={`${types}CompanyCode`}>
								<Select
									placeholder="请选择"
									allowClear
									fieldNames={{
										value: 'dictKey',
										label: 'dictValue',
									}}
									options={
										types === 'compulsory'
											? dictData?.compulsory_company_code
											: types === 'commercial'
											? dictData?.commercial_company_code
											: dictData?.carrier_company_code
									}
								/>
							</Form.Item>
						</Col>
						<Col sm={{span: 24}} md={{span: 12}}>
							<Form.Item label="被保人" name={`${types}Insured`}>
								<Input placeholder="请输入" />
							</Form.Item>
						</Col>
						<Col sm={{span: 24}} md={{span: 12}}>
							<Form.Item
								label="保单金额合计"
								name={`${types}TotalFee`}
								rules={[
									{
										pattern:
											/^([0-9]|[1-9]\d+)(\.\d{0,2})?$/,
										message: '小数点后不得超过两位',
									},
								]}>
								<InputNumber placeholder="请输入" />
							</Form.Item>
						</Col>
						<Col sm={{span: 24}} md={{span: 12}}>
							<Form.Item
								label="保险开始时间"
								name={`${types}StartTime`}>
								<DatePicker
									placeholder="请选择"
									format="YYYY-MM-DD"
								/>
							</Form.Item>
						</Col>
						<Col sm={{span: 24}} md={{span: 12}}>
							<Form.Item
								label="保险结束时间"
								name={`${types}EndTime`}>
								<DatePicker placeholder="请选择" />
							</Form.Item>
						</Col>
					</Row>
				</Col>
			</Row>
			{status !== 1 ? (
				<Row gutter={12}>
					<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
						<Form.Item
							label="延保始期"
							name={`${types}DelayStartTime`}>
							<DatePicker placeholder="请选择" />
						</Form.Item>
					</Col>
					<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
						<Form.Item
							label="延保止期"
							name={`${types}DelayEndTime`}>
							<DatePicker placeholder="请选择" />
						</Form.Item>
					</Col>
					<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
						<Form.Item
							label="延保时停保天数"
							name={`${types}DelayStopDays`}>
							<Input placeholder="请输入" />
						</Form.Item>
					</Col>
					<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
						<Form.Item label="延保单号" name={`${types}DelayNo`}>
							<Input placeholder="请输入" />
						</Form.Item>
					</Col>
					<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
						<Form.Item
							label="保险延顺止期"
							name={`${types}Deadline`}>
							<DatePicker placeholder="请选择" />
						</Form.Item>
					</Col>
					<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
						<Form.Item
							label="顺延天数"
							name={`${types}ContinuanceDays`}>
							<Input placeholder="请输入" />
						</Form.Item>
					</Col>
					<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
						<Form.Item
							label="延保复始时间"
							name={`${types}ContinuanceTime`}>
							<DatePicker placeholder="请选择" />
						</Form.Item>
					</Col>
					<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
						<Form.Item
							label="保险终止日期"
							name={`${types}AfterEndTime`}>
							<DatePicker placeholder="请选择" />
						</Form.Item>
					</Col>
					<Col span={16} style={{marginRight: '10px'}}>
						<Form.Item label="延保原因" name={`${types}StopReason`}>
							<TextArea
								maxLength={200}
								placeholder="请输入（最多200个字）"
								autoSize={{minRows: 3, maxRows: 6}}
							/>
						</Form.Item>
					</Col>
					{status === 2 ? (
						<>
							{' '}
							<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item
									label="停保时间"
									name={`${types}StopTime`}
									rules={[{required: true}]}>
									<DatePicker placeholder="请选择" />
								</Form.Item>
							</Col>
							<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item
									label="保险终止时间"
									name={`${types}TerminationTime`}>
									<DatePicker placeholder="请选择" disabled />
								</Form.Item>
							</Col>
						</>
					) : (
						<></>
					)}
				</Row>
			) : (
				<></>
			)}
		</>
	)

	return (
		<div className={styles.admittanceAdd}>
			{data?.compulsory?.id ? (
				<div className={styles.card}>
					<div className={styles.title}>
						<span> {customizeHeader('交强险保单')}</span>
						<span
							className={styles.type}
							style={{
								color:
									data?.compulsory
										?.compulsoryStopDelayStatus === 1
										? '@primary-color'
										: '#FF2E30',
							}}>
							{getOutOfWarranty(
								data?.compulsory?.compulsoryStopDelayStatus,
							)}
						</span>
					</div>
					<Form
						form={compulsoryForm}
						name="compulsory"
						layout="horizontal"
						labelCol={{flex: '140px'}}
						labelAlign="right"
						labelWrap
						initialValues={{remember: true}}
						autoComplete="off"
						disabled={type === 'view'}>
						{getForm(
							data?.compulsory?.compulsoryStopDelayStatus,
							'compulsory',
						)}
					</Form>
				</div>
			) : (
				''
			)}
			{data?.commercial?.id ? (
				<div className={styles.card}>
					<div className={styles.title}>
						<span> {customizeHeader('商业险保单')}</span>
						<span
							className={styles.type}
							style={{
								color:
									data?.commercial
										?.commercialStopDelayStatus === 1
										? '@primary-color'
										: '#FF2E30',
							}}>
							{getOutOfWarranty(
								data?.commercial?.commercialStopDelayStatus,
							)}
						</span>
					</div>
					<Form
						form={commercialForm}
						name="commercial"
						layout="horizontal"
						labelCol={{flex: '140px'}}
						labelAlign="right"
						labelWrap
						autoComplete="off"
						disabled={type === 'view'}>
						{getForm(
							data?.commercial?.commercialStopDelayStatus,
							'commercial',
						)}
					</Form>
				</div>
			) : (
				''
			)}
			{data?.carrier?.id ? (
				<div className={styles.card}>
					<div className={styles.title}>
						<span> {customizeHeader('承运险保单')}</span>
						<span
							className={styles.type}
							style={{
								color:
									data?.carrier?.carrierStopDelayStatus === 1
										? '@primary-color'
										: '#FF2E30',
							}}>
							{getOutOfWarranty(
								data?.carrier?.carrierStopDelayStatus,
							)}
						</span>
					</div>
					<Form
						form={carrierForm}
						name="carrier"
						layout="horizontal"
						labelCol={{flex: '140px'}}
						labelAlign="right"
						labelWrap
						autoComplete="off"
						disabled={type === 'view'}>
						{getForm(
							data?.carrier?.carrierStopDelayStatus,
							'carrier',
						)}
					</Form>
				</div>
			) : (
				''
			)}
		</div>
	)
}

export default forwardRef(insuranceCard)
